package com.mmall.common;

import com.mmall.util.PropertiesUtil;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;
import redis.clients.jedis.JedisPoolConfig;

public class RedisPool {
    private static JedisPool pool;//jedis连接池
    private static Integer maxTotal = Integer.parseInt(PropertiesUtil.getProperty("redis.max.total", "20"));//最大连接数
    private static Integer maxIdel = Integer.parseInt(PropertiesUtil.getProperty("redis.max.idle", "10"));//在jedisPool中最大的的空闲jedis实例的个数
    private static Integer minIdel = Integer.parseInt(PropertiesUtil.getProperty("redis.min.idle", "2"));//在jedisPool中最小的空闲jedis实例的个数
    private static Boolean testOnBorrow = Boolean.parseBoolean(PropertiesUtil.getProperty("redis.test.borrow", "true"));//在borrow（借）一个jedis时，是否需要进行验证操作，如果赋值为true，则jedis是可以使用的
    private static Boolean testOnReturn = Boolean.parseBoolean(PropertiesUtil.getProperty("redis.test.return", "true"));//在borrow（借）一个jedis时，是否需要进行验证操作，如果赋值为true，则jedis是可以还回来的
    private static String ip = PropertiesUtil.getProperty("redis.ip");
    private static Integer port = Integer.parseInt(PropertiesUtil.getProperty("redis.port"));


    public static void initPool() {
        JedisPoolConfig config = new JedisPoolConfig();
        config.setMaxTotal(maxTotal);
        config.setMaxIdle(maxIdel);
        config.setMinIdle(minIdel);
        config.setTestOnBorrow(testOnBorrow);
        config.setTestOnReturn(testOnReturn);
        config.setBlockWhenExhausted(true);//连接耗尽时，是否发生阻塞，false会抛出异常，true阻塞直到超时抛出超时异常，默认为true
        pool = new JedisPool(config, ip, port, 1000 * 2);
    }

    static {
        initPool();
    }

    public static Jedis getJedis() {
        return pool.getResource();
    }

    public static void returnBrokenResourse(Jedis jedis) {
        pool.returnBrokenResource(jedis);
    }

    public static void returnResourse(Jedis jedis) {
        pool.returnResource(jedis);
    }

    public static void main(String[] args) {
        Jedis jedis = pool.getResource();
        jedis.set("2","bbb");
        pool.returnResource(jedis);

        pool.destroy();//临时销毁连接驰中的所有连接
        System.out.println("结束");
    }
}
